package com.java1412.dao.impl;

import com.java1412.dao.UserDao;
import com.java1412.entity.Users;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

/**
 * @author java1412
 * @create 2021-05-20 10:18
 */
@Repository
public class UserDaoImpl implements UserDao {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Override
    public int add(Users users) {
        return jdbcTemplate.update("insert into users(username,password) values(?,?)", users.getUsername(), users.getPassword());
    }

    @Override
    public int update(Users users) {
        return jdbcTemplate.update("UPDATE users set username=?, password=? where id=?", users.getUsername(), users.getPassword(), users.getId());
    }

    @Override
    public int delete(int id) {
        return jdbcTemplate.update("delete from users where id=?", id);
    }

    @Override
    public Users findUserById(int id) {

        Users users = jdbcTemplate.queryForObject("select * from users where id=?", new RowMapper<Users>() {
            @Override
            public Users mapRow(ResultSet rs, int rowNum) throws SQLException {
                Users users = new Users();
                users.setId(rs.getInt("id"));
                users.setUsername(rs.getString("username"));
                users.setPassword(rs.getString("password"));
                return users;
            }
        }, id);
        return users;
        // BeanPropertyRowMapper 使获取的 List 结果列表的数据库字段和实体类自动对应, 但是该方法已经过期
        // List<Users> list = jdbcTemplate.query("select * from user where id=?", new Object[]{id}, new BeanPropertyRowMapper<>(Users.class));
        // return list.size()>0?list.get(0):null;
    }

    @Override
    public List<Users> findUserList() {
        List<Users> usersList = jdbcTemplate.query("select * from users", new RowMapper<Users>() {
            @Override
            public Users mapRow(ResultSet rs, int rowNum) throws SQLException {
                Users users = new Users();
                users.setId(rs.getInt("id"));
                users.setUsername(rs.getString("username"));
                users.setPassword(rs.getString("password"));
                return users;
            }
        });
        return usersList;
        // 使用Spring的JdbcTemplate查询数据库，获取List结果列表，数据库表字段和实体类自动对应，可以使用BeanPropertyRowMapper
        // List<Users> list = jdbcTemplate.query("select * from users", new Object[]{}, new BeanPropertyRowMapper(Users.class));
        // return list.size() > 0 ? list : null;
    }
}
